package com.application.admin;

import com.application.common.OrderStatus;
import com.application.condition.OrderCondition;
import com.application.model.Order;
import com.application.service.OrderService;
import com.application.validate.OrderAdminValidator;
import com.application.validate.SuperAdminValidator;
import com.jfinal.aop.Before;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Page;
import com.platform.annotation.Controller;
import com.platform.mvc.base.BaseController;
import com.platform.mvc.user.User;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 订单接口
 * 客户端与后台订单状态对应关系：*****
 */
@Controller("/admin/order")
public class OrderController extends BaseController {

    OrderService orderService;

    /*
    获取订单列表
    param:
     */
    @Before(OrderAdminValidator.class)
    public void index() {
        int num = splitPage.getPageNumber();
        int size = splitPage.getPageSize();
        String key = getPara("_query.keyword");
        String sd = getPara("_query.startDate");
        String ed = getPara("_query.endDate");
        Integer status = getParaToInt("_query.status");
        String sno = getPara("_query.stationNo");
        int level = getParaToInt("_query.level", 0);
        Integer userid = getParaToInt("userid");

        if (userid == null) {//初始进入页面，判断是否有查询条件
            User user = User.dao.findByUsername(key);
            if (user == null) {
                if (level > 0) {
                    renderErr(400, "", "请先输入下单人手机号");
                    return;
                }
            } else {
                userid = user.getId();
            }
        }

        OrderCondition condition = new OrderCondition(sd, ed, status, sno, userid);
        condition.setLevel(level);
        condition.setId(getPara("id"));//用于商品评价页面查询订单详情
        condition.setType(getPara("_query.type"));
        condition.setKeyword(key);
        /*
        订单状态处理
         */
        List<Integer> statusArr = getAttr("client_status");
        Page<Order> page = Order.dao.findList(num, size, statusArr, condition);

        /*
        订单描述
         */
        page.getList().forEach(o -> {
            String desc = OrderStatus.map.getOrDefault(o.getInt("order_status"), "");
            if (o.get("station_id") != null && (o.getOrder_status() == OrderStatus.TAKE_OVER
                   || o.getOrder_status() == OrderStatus.PAY_OVER || o.getOrder_status() == OrderStatus.TAKE_WAIT)) {
            }
            o.put("order_status_desc", desc);
        });

//        splitPage.setList(page.getList());
        renderOk(page);
    }

    /*
    订单详情
    param:id
     */
    public void view() {
        Order order = Order.dao.findById(getPara());

        //修改小程序支付显示
        String type = order.getPay_type();
        if(StrKit.notBlank(type) && type.equalsIgnoreCase(Order.PAY_XCX)) {
            order.setPay_type(Order.PAY_WX);
        }

        renderOk(order);
    }

    @Before(SuperAdminValidator.class)
    public void delete() {
        String idStr = getPara() == null ? getPara("checkbox") : getPara();
        if (StrKit.notBlank(idStr)) {
            for (String id : idStr.split(",")) {
                Order order = Order.dao.findById(id);
                order.set("delete_time", getDate()).set("delete_userid", super.getCUserIds()).update();
            }
        } else {
            error(404, "订单不存在或已被删除。");
        }

        renderOk("refresh", "删除成功", null);
    }


    /*
    处理退款，
    参数：answer_result 同意1，拒绝2
         order_id，订单id
     */
    @Before(OrderAdminValidator.class)
    public void refund() {
        boolean f = orderService.handlerRefund(getParaToInt("order_id"), getParaToInt("answer_result"), getCUserId());
        if (f) {
            renderOk("refresh", "操作成功", null);
        } else {
            renderErr(500, "", "退款失败");
        }
    }

    /*
    订单关闭
     */
    @Before(SuperAdminValidator.class)
    public void close() {
        boolean f = Order.dao.cancel(getParaToInt("id"), getPara("desc"), getCUserId(), OrderStatus.CLOSED_OTHER);
        renderOk("refresh", "操作成功", null);
    }

    /*
    订单打印,参数id, version
    根据普通订单与自提订单区分打印模板
     */
    public void print() {
        Order order = Order.dao.findDetail(getParaToInt() == null ? getParaToInt("id") : getParaToInt());
        order.set("order_print_time", new Date());
        order.update();
        setAttr("o", order);
        String ver = getPara("version");
        String sno = order.get("station_no");
        render("/order/print" + ver + ".html");
    }

    /*
    打印订单列表
     */
    public void printList() {
        List<Order> list = new ArrayList<>();
        String ids = getPara("ids");
        int total = 0;
        BigDecimal totalAmount = new BigDecimal(0);
        setAttr("itemList", list);
        setAttr("total", total);
        setAttr("totalAmount", totalAmount);
        render("/order/print_list.html");
    }


    /**
     * 修改未支付订单价格,需要同时变更订单号，param：price
     */
    public void updatePrice() {
        int orderId = getParaToInt();
        String price = getPara("price");
        if (StrKit.notBlank(price)) {
            Order order = Order.dao.findById(orderId);
            if (order == null) {
                error(404, "订单不存在或已被删除。");
            } else if (order.getOrder_status() == OrderStatus.PAY_WAIT) {
                order.setOrder_no(Order.dao.getOrderNewNo(order));
                if (order.update()) {
                    success("refresh", "价格修改成功");
                } else {
                    error(500, "价格修改失败");
                }
            } else {
                error(400, "订单已关闭，禁止操作");
            }
        } else {
            error(400, "参数错误");
        }

    }

    /**
     * 确认收货
     *
     * @param id
     */
    @Deprecated
    public void receive() {
        Integer id = getParaToInt("id");
        Order order = Order.dao.findById(id);
        if (order.getOrder_status() != OrderStatus.TAKE_WAIT) {
            renderErr(400, "", "仅支持待确认收货订单");
            return;
        }
        boolean f = orderService.receiveProduct(getParaToInt("id"), getCUserId());
        if (f) {
            renderOk("refresh", "确认收货成功", null);
        } else {
            renderErr(500, "", "操作失败");
        }
    }
}
